package com.charles.seckillComponentSecurity.aspect;

import com.charles.seckillComponentCommon.exceptions.ServiceException;
import com.charles.seckillComponentSecurity.annotation.RolePermit;
import com.charles.seckillComponentSecurity.utils.ThreadUtil;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

/**
 * @author Charles-H
 * 权限检查切面
 */
@Aspect
@Component
public class RolePermitAspect {
    
    @Around("@annotation(com.charles.seckillComponentSecurity.annotation.RolePermit)")
    public Object around(ProceedingJoinPoint proceedingJoinPoint) throws Throwable {
        MethodSignature signature = (MethodSignature) proceedingJoinPoint.getSignature();
        RolePermit permits = signature.getMethod().getAnnotation(RolePermit.class);
        if (permits != null) {
            checkRole(permits.values());
        }
        try {
            Object obj = proceedingJoinPoint.proceed();
            return obj;
        } catch (Throwable throwable) {
            throw throwable;
        }
    }
    
    public void checkRole(String role) {
        Integer roleId = ThreadUtil.getUserLogin().getSysUser().getRole_id();
        // 注意：这边因为只对两个权限进行检查，所以这边直接确定id，如果要增加多的业务的话，需要再线程那边加多一项权限进行排查
        String[] roleList = role.split(":");
        
        if (roleList.length > 1) {
            if (roleId != 1 && roleId != 2) {
                throw new ServiceException("无权访问");
            }
        } else {
            if (roleList[0].equals("admin") && roleId != 1) {
                throw new ServiceException("无权访问");
            }
            if (roleList[0].equals("common") && roleId != 2) {
                throw new ServiceException("无权访问");
            }
        }
    }
    
}
